var StoryGroup = function(params) { this.data = params; }

StoryGroup.prototype.newStoryGroupSuccess = function(groupData) {
  //console.log("newGroupSuccess: " + JSON.stringify(groupData));
  if (!isMobile()) {
    $.facebox.close();
    $('#my_stories').html(groupData['my_stories']);
    $('#story_group_' + groupData['id']).find('.story_group_toggle').click();
  }
  else {
    location.href = '/mystories';
  }
}

StoryGroup.prototype.editStoryGroupSuccess = function(groupData) {
  //console.log("editGroupSuccess: " + JSON.stringify(groupData));
  if (!isMobile()) {
    $.facebox.close();
    $('#my_stories').html(groupData['my_stories']);
    $('#story_group_' + groupData['id']).find('.story_group_toggle').click();
  }
  else {
    location.href = '/mystories';
  }
}

StoryGroup.prototype.deleteStoryGroupSuccess = function(groupData) {
  //console.log("deleteGroupSuccess: " + JSON.stringify(groupData));
  $('#my_stories').html(groupData['my_stories']);
}

StoryGroup.prototype.uploadStoryGroupSuccess = function(groupData) {
  //console.log("uploadGroupSuccess: " + JSON.stringify(groupData));
  $('#my_stories').html(groupData['my_stories']);
}

StoryGroup.prototype.save = function(groupData, button) {
  $('.success_message').hide();
  $('#success_message').html('');
  if (button) {
		$(button).addClass('button_spinner');
		$("#save_new_group_button").unbind('click', saveNewGroup);
		$("#save_existing_group_button").unbind('click', saveExistingGroup);
	}

	var REQ_PATH = API2_PATH;
  switch(groupData.req_type) {
		case 'new':
			REQ_PATH += 'newstorygroup';
			break;
		case 'edit':
			REQ_PATH += 'editstorygroup';
			break;
		case 'del':
			REQ_PATH += 'deletestorygroup';
			break;
		case 'upload':
			REQ_PATH += 'uploadstorygroup';
			break;
	}
  //console.log("storygroup save: " + JSON.stringify(groupData));
  $.post(REQ_PATH, groupData, 
    (function(sg) {
      return function(data) {
        //console.log("storygroup save return: " + JSON.stringify(data));
        if (data) {
          if (data['error_count'] > 0) {
            sg.clearErrors(); 
            sg.showErrors(data);
						$("#save_new_group_button").bind('click', saveNewGroup);
						$("#save_existing_group_button").bind('click', saveExistingGroup);
            //console.log("save error: " + JSON.stringify(data));
          }
          else { 
            sg.clearErrors(); 
            if (groupData.req_type == 'new') {
              sg.newStoryGroupSuccess(data);
            }
            else if (groupData.req_type == 'edit') {
              sg.editStoryGroupSuccess(data);
            }
            else if (groupData.req_type == 'del') {
              sg.deleteStoryGroupSuccess(data);
            }
            else if (groupData.req_type == 'upload') {
              sg.uploadStoryGroupSuccess(data);
            }
          }
        }
        $('.button_spinner').removeClass('button_spinner');
      };
    })(this)
  );
}

StoryGroup.prototype.getGroupData = function() {
  var gdata = {};
  var fields = ['id', 'title', 'description', 'complete', 'ownerid'];

  for (var i = 0; i < fields.length; i++) {
    var fname = 'storygroup_' + fields[i];
    if (fname == 'storygroup_complete') {
      gdata[fields[i]] = $("input:radio[name='" + fname + "']:checked").val();
    }
    else {
      gdata[fields[i]] = $('#' + fname).val();
    }
  }

  // get whatever story ids are currently in the group
  gdata['textids'] = '';
	for (var i = 0; i < document.forms['groupform'].ingroup.options.length; i++) {
		if (i==0) {
			gdata['textids'] = document.forms['groupform'].ingroup.options[i].value
		}
		else {
			gdata['textids'] += "," + document.forms['groupform'].ingroup.options[i].value
		}
	}
  return gdata;
};

StoryGroup.prototype.clearErrors = function() {
  $('#errors').hide();
  //$('.upload_error').each(function(i) { $(this).removeClass('upload_error'); });
  $('#error_list').html('');
}

StoryGroup.prototype.showErrors = function(data) {
  if (data['error']) {
    $('#error_list').append('<li>' + data['error'] + '</li>');
  }
  if (data['errors']) {
    $.each(data['errors'], function(error_field, error_message){
      $('#error_list').append('<li>' + error_message + '</li>');
      //$('#storygroup_' + error_field).closest('.field_container').addClass('upload_error');
    });
  }
  $('#errors').show();
}

StoryGroup.prototype.init = function() {
  if ($('#storygroup_id').val() === 'new') {
    $('#save_new_group_button').show();
  } 
  else {
    $('#save_existing_group_button').show();
  }

  $('#storygroup_title').focus();

  $('#save_existing_group_button').bind('click', {sg:this}, saveExistingGroup);

  $('#save_new_group_button').bind('click', {sg:this}, saveNewGroup);
};


var saveNewGroup = function() {
	var groupData = sg.getGroupData();
	groupData['req_type'] = 'new';
	sg.save(groupData, this);
	return false;
};

var saveExistingGroup = function() {
	var groupData = sg.getGroupData();
	groupData['req_type'] = 'edit';
	sg.save(groupData, this);
	return false;
};
